package cn.itcast.action;

import java.util.List;
import java.util.Map;

import org.apache.struts2.interceptor.RequestAware;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.opensymphony.xwork2.util.ValueStack;

import cn.itcast.entity.Admin;
import cn.itcast.service.IAdminService;

public class AdminAction extends ActionSupport implements ModelDriven<Admin>,RequestAware{

	private Admin admin=new Admin();
	public void setAdmin(Admin admin) {
		this.admin = admin;
	}
	public Admin getAdmin() {
		return admin;
	}
	private Map<String, Object> request;
	@Override
	public void setRequest(Map<String, Object> request) {
		this.request = request;
	}
	
	@Override
	public Admin getModel() {
		return admin;
	}
	
	private IAdminService adminService;
	public void setAdminService(IAdminService adminService) {
		this.adminService = adminService;
	}
	public IAdminService getAdminService() {
		return adminService;
	}
	
	public String login(){
		
		Admin adminInfo = adminService.login(admin);
		
		if(adminInfo == null){
			return "loginfailed";
		}else {
			ActionContext.getContext().getSession().put("adminInfo", adminInfo);
			return "index";
		}
		
	}
	
	public String viewAdd(){
		return "register";
	}
	
	public String add(){
		
		adminService.register(admin);
		
		return "listAction";
	}
	
	public String loginout(){
		
		Map<String, Object> session = ActionContext.getContext().getSession();
		if(session!=null){
//			session.put("adminInfo", null);	// 1
			session.remove("adminInfo");	// 2
		}
		return "index";
	}
	
	public String listAdmin(){
		
		List<Admin> listadmin = adminService.getAll();
		request.put("listadmin", listadmin);
		
		return "listAdmin";
	}
	
	public String viewUpdatePwd(){
		
		Map<String, Object> session = ActionContext.getContext().getSession();
		Admin admin = (Admin) session.get("adminInfo");
		
		ValueStack stack = ActionContext.getContext().getValueStack();
		stack.pop();
		stack.push(admin);
		
		return "updatePwd";
	}
	
	public String updatePwd(){
		
		adminService.update(admin);
		
		Admin adminInfo = adminService.findById(admin.getId());
		
		ActionContext.getContext().getSession().put("adminInfo", adminInfo);
		
		return "listAction";
	}
	
}
